package cn.worldyao.demo.controller;

import cn.worldyao.demo.entity.*;
import cn.worldyao.demo.service.SysRoleService;
import cn.worldyao.demo.service.SysUserRoleService;
import cn.worldyao.demo.service.SysUserService;
import cn.worldyao.demo.util.ReturnSet;
import cn.worldyao.demo.util.Tools;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.Set;

/**
 * @author yaozi
 */
@RestController
public class TestController {

    @Autowired
    private SysUserService sysUserService;


    @CrossOrigin
    @PostMapping("/regedit")
    public ReturnSet regedit(@RequestBody SysUser sysUser) {
        if (sysUserService.save(sysUser)) {
            ReturnSet.success("注册成功");
        }
        return ReturnSet.fail("注册失败");
    }


//    @CrossOrigin
//    @RequestMapping(value = "/login", method = RequestMethod.POST)
//    public ReturnSet login(@RequestBody User user) {
//        System.out.println(user.getUsername() + " + " + user.getPassword());
//        if ("xuqing".equals(user.getUsername()) && "123456".equals(user.getPassword())) {
//            System.out.println("dddd");
//            return ReturnSet.success("登录成功");
//        }
//        return ReturnSet.fail("登陆失败");
//    }

    @PostMapping(value = "/api/login")
    @ResponseBody
    public ReturnSet login(@RequestBody SysUser requestUser) {
        String username = requestUser.getUsername();
        Subject subject = SecurityUtils.getSubject();
//        subject.getSession().setTimeout(10000);
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, requestUser.getPassword());
        try {
            subject.login(usernamePasswordToken);
            return ReturnSet.success(usernamePasswordToken);
        } catch (AuthenticationException e) {
            String message = "账号密码错误";
            return ReturnSet.fail(message);
        }
    }
}
